package com.leandom.studydemo.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.leandom.studydemo.R;
import com.leandom.studydemo.async.loader.DemoAsyncTaskLoader;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

public class AsyncTaskLoaderActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> {

    private static final String TAG = "DEMO";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asynctask_loader);
        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoaderManager.getInstance(AsyncTaskLoaderActivity.this).initLoader(1, null, AsyncTaskLoaderActivity.this);
            }
        });

        findViewById(R.id.btn_restart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // LoaderManager.getInstance(AsyncTaskLoaderActivity.this).destroyLoader(1);
                LoaderManager.getInstance(AsyncTaskLoaderActivity.this).restartLoader(1, null, AsyncTaskLoaderActivity.this);
            }
        });

    }

    @NonNull
    @Override
    public Loader<String> onCreateLoader(int id, @Nullable Bundle args) {
        Log.d(TAG, "onCreateLoader: " + id);
        return new DemoAsyncTaskLoader(this);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<String> loader, String data) {
        Log.d(TAG, "onLoadFinished: " + data);
        // 当app进入后台的时候，该方法并不会执行，重新进入前台的时候onStartLoading会再次回调
    }

    @Override
    public void onLoaderReset(@NonNull Loader<String> loader) {
        Log.d(TAG, "onLoaderReset: " + loader.getId());
    }
}
